package com.ssm.subject.domain.util;


import com.alibaba.fastjson.JSON;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * 本地缓存工具类
 */
@Component
public class CacheUtil<V> {

    private Cache<String, String> localCache = CacheBuilder.newBuilder()
            .maximumSize(5000) //最大容量
            .expireAfterWrite(10, TimeUnit.SECONDS) //最大容量、过期时间
            .build();

    /**
     * @param cacheKey 缓存key
     * @param clazz 声明json序列化类型
     * @param function 由调用方自己写具体方法
     * @return
     */
    public List<V> getResult(String cacheKey, Class<V> clazz, Function<String, List<V>> function) {
        String content = localCache.getIfPresent(cacheKey);
        if(StringUtils.isNotBlank(content)) {
            return JSON.parseArray(content, clazz);
        }
        List<V> resultList = function.apply(cacheKey);
        if(!CollectionUtils.isEmpty(resultList)) {
            localCache.put(cacheKey, JSON.toJSONString(resultList));
        }
        return resultList;
    }

}
